﻿using System;
using System.Configuration;
using System.Reflection;
using MongoDAO.Attributes;

namespace MongoDAO.Configuration
{
    public static class MongoConfigurationSettings
    {
        public static string GetConnectionString(string connectionStringName = "MongoServerSettings")
        {
            var connectionStringSettings = ConfigurationManager.ConnectionStrings[connectionStringName];
            if (connectionStringSettings == null)
                throw new NullReferenceException("connectionStringSettings");
            return connectionStringSettings.ConnectionString;
        }

        public static string GetCollectionName<T>()
        {
            var attribute = GetCustomAttribute<T>(typeof(MongoCollectionNameAttribute));
            if (attribute == null)
                throw new NullReferenceException("MongoCollectionName Attribute not specified.");
            return ((MongoCollectionNameAttribute)attribute).collectionName;
        }

        public static string GetCollectionName(MemberInfo memberInfo)
        {
            var attribute = GetCustomAttribute(typeof(MongoCollectionNameAttribute), memberInfo);
            if (attribute == null)
                throw new NullReferenceException("MongoCollectionName Attribute not specified");
            return ((MongoCollectionNameAttribute)attribute).collectionName;
        }

        private static Attribute GetCustomAttribute<T>(Type attribute)
        {
            if (attribute == null) throw new ArgumentNullException("attribute");
            return Attribute.GetCustomAttribute(typeof(T), attribute);
        }

        private static Attribute GetCustomAttribute(Type attribute, MemberInfo memberInfo)
        {
            if (attribute == null) throw new ArgumentNullException("attribute");
            return Attribute.GetCustomAttribute(memberInfo, attribute);
        }
    }
}
